<template>
  <div class="cmt">
      <h2>发表评论</h2>
      <hr>
      <textarea placeholder="请输入您想评论的字，不要超过120字" maxlength="120" v-model="msg"></textarea>
      <mt-button type="primary" size="large" @click="addCmt">发表评论</mt-button> 
      <div class="content" v-for="(item, index) in cmtData" :key="index">
          <div class="cmt_header">第{{ index + 1 }}楼&nbsp;&nbsp;用户：{{ item.user_name }}&nbsp;&nbsp;发表时间：{{ item.add_time | dateStrFormat }}</div>
          <div class="cmt_content">{{ item.content }}</div>
      </div>
      <mt-button plain type="danger" size="large" @click="getMoreData">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from 'mint-ui'
export default {
  data(){
      return {
          pageindex: 1,
          cmtData: [],
          msg: ''
      }
  },
  created(){
      this.getCmtData();
  },
  methods:{
      getCmtData(){
          this.$http.get("api/getcomments/"+ this.$route.params.id +"?pageindex=" + this.pageindex).then(result => {
            //   console.log(result.body)
            if(result.body.status === 0) {
                this.cmtData = this.cmtData.concat(result.body.message);
            } else {
                Toast('获取评论数据失败');
            }
          })
      },
      getMoreData(){
        this.pageindex++;
        this.getCmtData();
      },
      addCmt(){
          if(this.msg.trim().length === 0) {
              return Toast('添加评论不能为空');
          }
          this.$http.post('api/postcomment/' + this.$route.params.id, { content: this.msg.trim() },{ emulateJSON: true } ).then(result => {
            //   console.log(result.body)
            if(result.body.status === 0) {
                var cmt = {
                    user_name: '匿名用户',
                    add_time: Date.now(),
                    content: this.msg.trim()
                };
                this.cmtData.unshift(cmt);
                this.msg = '';
            }
          })
      }     
  },
  props:['this.$route.params.id']
}
</script>

<style lang="less" scoped>
    .cmt {
        margin: 5px;
        h2 {
            font-size: 18px;
        }
        textarea {
            height: 100px;
            margin: 0;
            font-size: 13px;
        }
        .content {
            font-size: 13px;
            .cmt_header {
                background-color: #ccc;
                line-height: 35px;
                padding: 0 5px;
                margin-top: 5px;
            }
            .cmt_content {
                line-height: 35px;
                padding: 0 30px;
            }
        }
    }
</style>


